package com.hhf.feiojquestionservice.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhf.feiojapiservice.client.JudgeFeignClient;
import com.hhf.feiojapiservice.client.UserFeignClient;
import com.hhf.feiojcommonservice.common.ErrorCode;
import com.hhf.feiojcommonservice.constant.CommonConstant;
import com.hhf.feiojcommonservice.constant.RabbitMQConstant;
import com.hhf.feiojcommonservice.exception.BusinessException;
import com.hhf.feiojcommonservice.model.entity.Question;
import com.hhf.feiojcommonservice.model.entity.QuestionSubmit;
import com.hhf.feiojcommonservice.model.entity.User;
import com.hhf.feiojcommonservice.model.enums.QuestionSubmitLanguageEnum;
import com.hhf.feiojcommonservice.model.enums.QuestionSubmitStatusEnum;
import com.hhf.feiojcommonservice.utils.SqlUtils;
import com.hhf.feiojquestionservice.mapper.QuestionSubmitMapper;
import com.hhf.feiojquestionservice.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.hhf.feiojquestionservice.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.hhf.feiojquestionservice.model.vo.QuestionSubmitVO;
import com.hhf.feiojquestionservice.rabbit.publisher.JudgeMessagePublisher;
import com.hhf.feiojquestionservice.service.QuestionService;
import com.hhf.feiojquestionservice.service.QuestionSubmitService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @author 86138
 * @description 针对表【question_submit(问题提交)】的数据库操作Service实现
 * @createDate 2024-10-25 20:01:26
 */
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
        implements QuestionSubmitService {

    @Resource
    private QuestionService questionService;


    @Resource
    private UserFeignClient userFeignClient;


    @Resource
    private JudgeMessagePublisher judgeMessagePublisher;

    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        // 校验编程语言是否合法
        String language = questionSubmitAddRequest.getLanguage();
        QuestionSubmitLanguageEnum questionSubmitLanguageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if (questionSubmitLanguageEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "暂无该语言");
        }
        // 判断实体是否存在，根据类别获取实体
        long userId = loginUser.getId();
        Long questionId = questionSubmitAddRequest.getQuestionId();
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //断用户是否提交过该类作答,若提交过,查看提交的列表里面是否有status=WAITING的状态,若有,则不创建新对象
        QueryWrapper<QuestionSubmit> wrapper = new QueryWrapper<>();
        wrapper.eq("question_id",questionId);
        wrapper.eq("user_id",userId);
        wrapper.select("status");
        List<Integer> statusList = this.list(wrapper).stream().map(QuestionSubmit::getStatus).collect(Collectors.toList());
        if (statusList.contains(QuestionSubmitStatusEnum.RUNNING.getValue())){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "问题正在判题中,请不要重复提交");
        }


        //每个用户串行提交题目
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setUserId(userId);
        questionSubmit.setLanguage(language);
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        //设置初始状态
        questionSubmit.setJudgeInfo("{}");
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        boolean save = this.save(questionSubmit);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据插入失败");
        }
        Long questionSubmitId = questionSubmit.getId();

        //rabbitMQ 实现异步判题服务,替代下方的方法
        judgeMessagePublisher.sendMessage(RabbitMQConstant.EXCHANGE_NAME,RabbitMQConstant.ROUTING_KEY,String.valueOf(questionSubmitId));

//        //异步传入判题服务
//        CompletableFuture.runAsync(() -> {
//            //执行判题服务
//            judgeFeignClient.doJudge(questionSubmitId);
//        });



        return questionSubmitId;
    }

    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.eq(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status) != null, "status", status);
        queryWrapper.eq("deleted", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;

    }


    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        // 脱敏：仅本人和管理员能看见自己（提交 userId 和登录用户 id 不同）提交的代码
        long userId = loginUser.getId();
        // 处理脱敏
        if (userId != questionSubmit.getUserId() && !userFeignClient.isAdmin(loginUser)) {
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;

    }

    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, HttpServletRequest request) {

        User loginUser = userFeignClient.getCurrentUser();

        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollectionUtils.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        //关联查询用户和问题信息
        Set<Long> useIdSet = questionSubmitList.stream().map(QuestionSubmit::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userFeignClient.listByIds(useIdSet).stream().collect(Collectors.groupingBy(User::getId));

        Set<Long> questionIdSet = questionSubmitList.stream().map(QuestionSubmit::getQuestionId).collect(Collectors.toSet());
        Map<Long, List<Question>> questionIdQuestionListMap = questionService.listByIds(questionIdSet).stream().collect(Collectors.groupingBy(Question::getId));


        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
                .map(questionSubmit -> {
                    QuestionSubmitVO questionSubmitVO = getQuestionSubmitVO(questionSubmit, loginUser);
                    //关联用户
                    Long userId = questionSubmit.getUserId();
                    User user = null;
                    if (userIdUserListMap.containsKey(userId)) {
                        user = userIdUserListMap.get(userId).get(0);
                    }
                    questionSubmitVO.setUserVO(userFeignClient.getUserVO(user));
                    //关联问题
                    Long questionId = questionSubmit.getQuestionId();
                    Question question = null;
                    if (questionIdQuestionListMap.containsKey(questionId)) {
                        question = questionIdQuestionListMap.get(questionId).get(0);
                    }
                    questionSubmitVO.setQuestionVO(questionService.getQuestionVO(question,request));
                    return questionSubmitVO;
                })
                .collect(Collectors.toList());
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }
}




